#
#!/bin/bash
#
# $Id:$
#
# tracd:       Starts the trac Server
#
# Version:      @(#) /etc/init.d/tracd 0.01
#
# chkconfig: 2345 90 10
# description: Starts and stops the trac Server at boot time and shutdown. \
#              It also takes care of (re-)generating font lists.
#
# processname: tracd
# config: read the install file to configuration
#
#tracd --port 8000 /var/trac/projeto

# Source function library.
. /etc/init.d/functions

prog=tracd2
KILL='/bin/kill -9'
lock=/var/lock/subsys
cmd=/usr/sbin/tracd
cont=-1
ARQCONF=config.tracd
EXT=tracd

#test -e $ARQCONF && echo "É necessário criar o arquivo $ARQCONF"||exit 0

[ ! -e $ARQCONF ] && echo "É necessário criar o arquivo $ARQCONF" && exit 0


function _VERIF(){
        NUM=$[ $1 & 1 ]
 
         if [ $NUM -eq 0 ]; then
                 echo 1
         else
                 echo 0
         fi
 }
 
for i in `cat $ARQCONF`
do
        let cont+=1
	if [ `_VERIF $cont` -ne 0 ]; then
                PORT[`expr $cont \/ 2`]=$i
        else
                DIR[`expr $cont \/ 2`]=$i
        fi
#       echo -n ${DIR[$cont]}   # valor do array DIR na posição cont
#       echo -n ${PORT[$cont]}  # valor do array PORT na posição cont
done

#for ((i=0; i <= `expr $cont \/ 2`; i++))
#do
#        echo -n "${PORT[$i]} "
#        echo "${DIR[$i]}"
#        echo " "
#done

RETVAL=0

start(){
	for ((i=0; i <= `expr $cont \/ 2`; i++))
	do
		echo -n "Iniciando o contexto <${DIR[$i]}> porta <${PORT[$i]}>: "
		if [ ! -e $lock/${PORT[$i]}.tracd ]; then
			$cmd --port ${PORT[$i]} ${DIR[$i]}& 2> /dev/null
			RETVAL=$?
			[ $RETVAL -eq 0 ] && echo $! > $lock/${PORT[$i]}.$EXT 
			test -e $lock/${PORT[$i]}.$EXT&&echo_success
		else
			echo
			echo -n " Já está em execução!"&&echo_failure
		fi
		echo
	done
	return $RETVAL
}

startone(){
#	$T01& echo $! > $lock/tracd01.pid
#	$T02& echo $! > $lock/tracd02.pid
echo
}


stop(){
	for ((i=0; i <= `expr $cont \/ 2`; i++))
	do
		echo -n "Finalizando o contexto <${DIR[$i]}> porta <${PORT[$i]}>: "
		if [ -e $lock/${PORT[$i]}.tracd ]; then
			$KILL $(cat $lock/${PORT[$i]}.$EXT)
			rm -f $lock/${PORT[$i]}.$EXT 
			[ ! -e $lock/${PORT[$i]}.$EXT ] && echo_success
		else
			echo
			echo -n " Já finalizado!"&&echo_failure
		fi
		echo
	done
}

restart(){
	stop
	start
}

case "$1" in
  startone)
	startone
	;;
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
	restart
    	;;
  reload)
       restart 
        ;;
  status)
        
        ;;
  *)
        echo $"Use: $prog {startone|start|stop|status|restart|reload}"
        exit 1
esac
